package com.lemon.core.utils;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 李猛
 * @datetime 2023/10/14 15:43
 * @description 类对象
 */
@Slf4j
public class FileUtil {
    public static Map<String, String> upload(MultipartFile file, String path, String baseUrl) {
        log.info("文件上传");
        //1.获取当前日期的字符串
        String date = LocalDate.now().format(LocalDateUtil.dateFormatter7);

        //2.获取文件名
        String originName = file.getOriginalFilename();

        //3.截取文件后缀，包括.
        String lastName = originName.substring(originName.lastIndexOf("."));

        //4.生成新的名字
        String name = RandomUtil.randomString(30).replaceAll("/","") + lastName;

        //5.保存的全路径
        String fullPath = (path.endsWith("/") ? path : (path + "/")) + date + "/" + name;

        //6.判断路径是否存在
        File files = new File(fullPath);
        if (!files.getParentFile().exists()) {
            files.getParentFile().mkdirs();
        }

        //7.保存上传文件
        try {
            file.transferTo(files);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }

        //8.生成读取文件的url
        String url = (baseUrl.endsWith("/") ? baseUrl : (baseUrl + "/")) + date + "/" + name;

        //9.封装返回值
        Map<String, String> result = new HashMap<>();
        result.put("originName", originName);
        result.put("name", name);
        result.put("path", fullPath);
        result.put("url", url);
        return result;
    }
}
